/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package xyz.hanks.smallbang.adapters;

import xyz.hanks.library.bang.SmallBangView;
import xyz.hanks.smallbang.ListBean;
import xyz.hanks.smallbang.ResourceTable;
import java.util.List;
import ohos.agp.components.*;
import ohos.app.Context;

public class ListAdapter extends BaseItemProvider {
  private final Context context;
  private List<ListBean> list;

  public ListAdapter(Context context, List<ListBean> listBeans) {
    this.context = context;
    this.list = listBeans;
  }

  @Override
  public int getCount() {
    return list == null ? 0 : list.size();
  }

  @Override
  public Object getItem(int position) {
    if (list != null && position >= 0 && position < list.size()) {
      return list.get(position);
    }
    return null;
  }

  @Override
  public long getItemId(int i) {
    return i;
  }

  /**
   * @noinspection checkstyle:NeedBraces
   */
  @Override
  public Component getComponent(int i, Component convertComponent,
                                ComponentContainer componentContainer) {
    final Component item;
    ViewHolder holder;
    if (convertComponent == null) {
      item = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_list_row, null, false);
      holder = new ViewHolder(item);
      item.setTag(holder);
    } else {
      item = convertComponent;
      holder = (ViewHolder) item.getTag();
    }
    holder.starButton.setClickedListener(new Component.ClickedListener() {
      @Override
      public void onClick(Component component) {
        if (list.get(i).getLiked()) {
          holder.starButton.setLiked(false);
          list.get(i).setLiked(false);
        } else {
          holder.starButton.setLiked(true);
          list.get(i).setLiked(true);
        }
        System.out.println("msz: " + i);
      }
    });
    holder.title.setText(list.get(i).getTitle());
    holder.starButton.setStatus(list.get(i).getLiked());
    return item;
  }

  public class ViewHolder {
    Text title;
    SmallBangView starButton;

    ViewHolder(Component component) {
      title = (Text) component.findComponentById(ResourceTable.Id_title);
      starButton = (SmallBangView) component.findComponentById(ResourceTable.Id_star_button);
    }
  }
}
